package com.longge;

import java.util.ArrayList;

public class CanSortArray {

    public boolean canSortArray(int[] nums) {

        ArrayList<Integer> max = new ArrayList<>();
        ArrayList<Integer> min = new ArrayList<>();

        int curMax = Integer.MIN_VALUE, curMin = Integer.MAX_VALUE;
        for (int i = 0; i < nums.length; i++) {
            if (i == nums.length - 1 || countBits(nums[i]) != countBits(nums[i + 1])) {
                curMax = Math.max(curMax, nums[i]);
                curMin = Math.min(curMin, nums[i]);
                max.add(curMax);
                min.add(curMin);
                curMax = Integer.MIN_VALUE;
                curMin = Integer.MAX_VALUE;
            } else {
                curMax = Math.max(curMax, nums[i]);
                curMin = Math.min(curMin, nums[i]);
            }
        }

        if (checkAsc(min, max)) {
            return true;
        }



        return false;
    }



    private boolean checkAsc(ArrayList<Integer> min, ArrayList<Integer> max) {
        for (int i = 0; i < max.size() - 1; i++) {
            if (max.get(i) >= min.get(i + 1)) {
                return false;
            }
        }
        return true;
    }

    public int countBits(int num) {
        int count = 0;
        while (num != 0) {
            count += num & 1; // 检查最低位是否为1
            num >>= 1; // 右移一位，相当于除以2
        }
        return count;
    }

    public static void main(String[] args) {
        CanSortArray canSortArray = new CanSortArray();
        canSortArray.canSortArray(new int[]{35,143,127,254});

        System.out.println(canSortArray.countBits(127));
        System.out.println(canSortArray.countBits(254));
        System.out.println(canSortArray.countBits(143));
    }



}
